<?php
/**
 * Created by PhpStorm.
 * Script Name: Crontab.php
 * Create: 2023/3/28 7:37
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\service;


use app\common\model\Crontab as CrontabM;

class Crontab extends Common
{

    /**
     * 开启个微定时任务
     * @throws \think\db\exception\DbException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function botTaskStart(){
        $company_id = intval(session(SESSION_ADMIN)['id']);
        //群发任务
        $url = \request()->domain() . '/app/wechat/crontab/bot/runtask';
        if(! CrontabM::where('company_id', $company_id)
            ->where('module', 'wechat')
            ->where('url', $url)
            ->count()){
            CrontabM::create([
                'company_id' => $company_id,
                'module' => 'wechat',
                'url' => $url,
                'rule' => '0 */1 * * * *'
            ]);
        }

        //定时发圈
        $url = \request()->domain() . '/app/wechat/crontab/bot/sendMoments';
        if(! CrontabM::where('company_id', $company_id)
            ->where('module', 'wechat')
            ->where('url', $url)
            ->count()){
            CrontabM::create([
                'company_id' => $company_id,
                'module' => 'wechat',
                'url' => $url,
                'rule' => '0 */1 * * * *'
            ]);
        }
        //跟圈
        $url = \request()->domain() . '/app/wechat/crontab/bot/followMoments';
        if(! CrontabM::where('company_id', $company_id)
            ->where('module', 'wechat')
            ->where('url', $url)
            ->count()){
            CrontabM::create([
                'company_id' => $company_id,
                'module' => 'wechat',
                'url' => $url,
                'rule' => '0 */1 * * * *'
            ]);
        }
    }

    /**
     * 关闭个微定时
     * @throws \think\db\exception\DbException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function botTaskStop(){
        $company_id = intval(session(SESSION_ADMIN)['id']);
        //群发任务
        $url_arr = [
            \request()->domain() . '/app/wechat/crontab/bot/runtask',
            \request()->domain() . '/app/wechat/crontab/bot/sendMoments',
            \request()->domain() . '/app/wechat/crontab/bot/followMoments'
        ];
        CrontabM::where('company_id', $company_id)
            ->where('module', 'wechat')
            ->where('url', 'in', $url_arr)
            ->delete();
    }
}